package com.lxx.jmb2c.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxx.jmb2c.dto.AdminLoginDTO;
import com.lxx.jmb2c.entity.Admin;
import com.lxx.jmb2c.entity.AdminRole;
import com.lxx.jmb2c.exceptions.BusinessException;
import com.lxx.jmb2c.handlers.BaseContextHandler;
import com.lxx.jmb2c.mapper.AdminMapper;
import com.lxx.jmb2c.service.AdminRoleService;
import com.lxx.jmb2c.service.AdminService;
import com.lxx.jmb2c.utils.JwtUtil;
import com.lxx.jmb2c.vo.AdminInfoVO;
import com.lxx.jmb2c.vo.AdminLoginVO;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;

/**
 * <p>
 * 管理员用户表 服务实现类
 * </p>
 *
 * @author wuyunbin
 * @since 2025-07-07
 */
@Slf4j
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private HttpServletRequest request;

    @Resource
    private AdminRoleService adminRoleService;

    @Override
    public AdminLoginVO login(AdminLoginDTO adminLoginDTO) {
        LambdaQueryWrapper<Admin> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasText(adminLoginDTO.getUsername()) ,Admin::getEmail,adminLoginDTO.getUsername());
        Admin admin = this.getOne(wrapper);

        if(admin==null){
            throw new BusinessException("账号不存在或密码错误");
        }

        log.info("password:{}",passwordEncoder.encode(adminLoginDTO.getPassword()));
        if(!passwordEncoder.matches(adminLoginDTO.getPassword(),admin.getPassword())){
            throw new BusinessException("账号不存在或密码错误");
        }

        HashMap<String,Object> map=new HashMap<>();
        map.put("id",admin.getId());

        String token = jwtUtil.generateToken(map);

        AdminLoginVO adminLoginVO=new AdminLoginVO();
        adminLoginVO.setAvatar(admin.getAvatar());
        adminLoginVO.setToken(token);

        return adminLoginVO;
    }

    @Override
    public AdminInfoVO info() {
        Long id = BaseContextHandler.get();
        log.info("id:{}",id);
        Admin admin = this.getById(id);
        //admin->adminLoginVO
        AdminInfoVO adminInfoVO=new AdminInfoVO();
        adminInfoVO.setName(admin.getAdminName());
        adminInfoVO.setAvatar(admin.getAvatar());
        adminInfoVO.setEmail(admin.getEmail());
        //admin的role_id 转成  tb_admin_role 的角色名
        AdminRole adminRole = adminRoleService.getById(admin.getRoleId());
        adminInfoVO.setRole(adminRole.getName());

        return adminInfoVO;
    }
}
